from random import choice
import hashlib
import urllib2
import json
import base64
import hmac

def parse_signed_request(signed_request, app_secret):
    """Return dictionary with signed request data.
    Code taken from https://github.com/facebook/python-sdk"""
    try:
        l = signed_request.split('.', 2)
        encoded_sig = str(l[0])
        payload = str(l[1])
    except IndexError:
        raise ValueError("'signed_request' malformed")
    
    sig = base64.urlsafe_b64decode(encoded_sig + "=" * ((4 - len(encoded_sig) % 4) % 4))
    data = base64.urlsafe_b64decode(payload + "=" * ((4 - len(payload) % 4) % 4))

    data = json.loads(data)

    if data.get('algorithm').upper() != 'HMAC-SHA256':
        raise ValueError("'signed_request' is using an unknown algorithm")
#    else:
#        expected_sig = hmac.new(unicode(app_secret), msg=payload, digestmod=hashlib.sha256).digest()

#     if sig != expected_sig:
#         raise ValueError("'signed_request' signature mismatch")
#     else:
#         return data
#       
    return data

def like_us(signed_request, app_secret):
    data = parse_signed_request(signed_request, app_secret)

    if data.get('page').get('liked'):
        return True;
    else:
        return False;